package com.yootk;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Account { // 账户信息类
    private String name; // 账户名称
    private int asset; // 账户资金
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); // 读写锁

    public Account(String name, int asset) { // 构造方法
        this.name = name; // 属性赋值
        this.asset = asset; // 属性赋值
    }

    public void save(int asset) { // 写锁操作方法
        this.readWriteLock.writeLock().lock(); // 独占的写锁
        try {
            this.asset += asset; // 账户资金累加
            TimeUnit.SECONDS.sleep(1); // 模拟延迟
            System.out.println("[" + Thread.currentThread().getName() +
                    "]修改银行资产，当前的资产为：" + (this.asset / 100.0));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.readWriteLock.writeLock().unlock(); // 释放写锁
        }
    }

    public String toString() { // 读锁操作方法
        this.readWriteLock.readLock().lock(); // 共享读锁
        try {
            TimeUnit.MILLISECONDS.sleep(100); // 模拟延迟
            return "[" + Thread.currentThread().getName() +
                    "]账户余额：" + (this.asset / 100.0);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            this.readWriteLock.readLock().unlock(); // 释放读锁
        }
    }
}

public class YootkDemo8 {
    public static void main(String[] args) {
        Account account = new Account("张三", 10000); // 初始资金100.00元

        // 创建存款线程
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                account.save(5000); // 每次存款50.00元
            }, "存款线程-" + i).start();
        }

        // 创建查询线程
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                System.out.println(account.toString());
            }, "查询线程-" + i).start();
        }
    }
}